package com.encryptdemo.encrypt3.handler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;

import com.encryptdemo.encrypt3.annotation.EncDec;
import com.encryptdemo.encrypt3.domain.CoreConstant;
import com.encryptdemo.encrypt3.domain.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.nio.charset.StandardCharsets;

/**
 * 所有的响应都会走到这里
 * 对响应参数进行加密
 *
 * @author kun.li
 */
@RestControllerAdvice
@Slf4j
public class HandlerResponseBodyAdvice implements ResponseBodyAdvice<ResponseResult> {


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查方法上是否有 EncDec 注解并且 resultEnc 属性为 true
        EncDec encDecAnnotation = returnType.getMethod().getAnnotation(EncDec.class);
        return encDecAnnotation != null && encDecAnnotation.resultEnc();
    }

    @Override
    public ResponseResult beforeBodyWrite(ResponseResult body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Object data = body.getData();
        if (data != null) {
            log.info("接口加密前返回数据:{}", data);
            String encodeResponseData = SecureUtil.aes(CoreConstant.AES_KEY.getBytes()).encryptHex(JSONUtil.toJsonStr(data).getBytes(StandardCharsets.UTF_8));
            log.info("接口加密后返回数据:{}", encodeResponseData);
            body.setData(encodeResponseData);
        }
        return body;
    }
}
